package cn.slipi.admin.common.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.SecureRandom;

/**
 * @author litao
 */
public class SecUtil {

    private static Key key;
    public static final String SALT = "0ca1@75b9c0f76!a831d895e2693#32461";


    static {
        try {
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            String keyKey = "secret";
            secureRandom.setSeed(keyKey.getBytes());
            generator.init(secureRandom);
            key = generator.generateKey();
            generator = null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 对字符串进行加密，返回BASE64的加密字符串
     *
     * @param str
     * @return
     */
    public static String encrypt(String str) {
        try {
            String merge = str + SALT;
            byte[] strBytes = merge.getBytes(StandardCharsets.UTF_8);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptStrBytes = cipher.doFinal(strBytes);
            return new String(Base64.encodeBase64(encryptStrBytes));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 对BASE64加密字符串进行解密
     *
     * @param sec
     * @return
     */
    public static String decrypt(String sec) {
        try {
            byte[] strBytes = Base64.decodeBase64(sec);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] encryptStrBytes = cipher.doFinal(strBytes);
            String tmp = new String(encryptStrBytes, StandardCharsets.UTF_8);
            return tmp.replace(SALT, "");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
